<?php
/**
 * @file: SimpleDBApi_MS_PDO.php
 * @brief: mssqlserver pdo的SimpleDBApi实现
 *
 * @author enic errorcpp@qq.com
 * @version 0.0.0.1
 * @date 2018-02-10
 */

include_once "SimpleDBApi.php";

/*
 * @brief: SQLServer访问的简单API接口
 */
class SimpleDBApi_MS_PDO implements SimpleDBApi
{
    private $m_PDOObj;           /**< {PDO} PDO对象 */
    private $m_PDOStatementObj;  /**< {PDOStatement} prepare返回的预处理对象 */
    

    public function Connect($strIp, $nPort, $strDatabase, $strUserName, $strPassword)
    {
        $dbConnString = "sqlsrv:Server=" . $strIp . "," . $nPort . ";Database=" . $strDatabase;
        //echo $dbConnString . "<br/>";
        try 
        {
            // 用持久链接打开数据库 array(PDO::ATTR_PERSISTENT => true)
            $this->m_PDOObj = new PDO($dbConnString, $strUserName, $strPassword);
            // 防止注入
            $this->m_PDOObj->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
        }
        catch(PDOException $e)
        {
            echo "数据库访问异常：" . $e->getMessage();
            
            return false;
        }
        
        return true;
    }
    
    public function Prepare($strSQL)
    {
        try
        {
            $this->m_PDOStatementObj = $this->m_PDOObj->prepare($strSQL);
        }
        catch(PDOException $e)
        {
            echo "数据库访问异常：" . $e->getMessage();
            
            return false;
        }
        
        return true;
    }
    
    public function BindParam($nNum, $param)
    {
        try
        {
            $this->m_PDOStatementObj->bindParam($nNum, $param);
        }
        catch(PDOException $e)
        {
            echo "数据库访问异常：" . $e->getMessage();
            
            return false;
        }
        
        return true;
    }
    
    public function Execute()
    {
        $ret = false;
        
        try
        {
            $ret = $this->m_PDOStatementObj->execute();
            //var_dump($this->m_PDOStatementObj->errorInfo());
        }
        catch(PDOException $e)
        {
            echo "数据库访问异常：" . $e->getMessage();
            
            return false;
        }
        
        return $ret;
    }
    
    public function Fetch()
    {
        return $this->m_PDOStatementObj->fetch(); 
    }
}

